<template>
  <div id="addQuestion">
    <h2 style="margin-bottom: 32px;">设置题目</h2>
    <!-- 表单 -->
    <a-form :model="questionContent" ref="formRef" :style="{ width: '580px' }" @submit="handleSubmit" >
      <!-- {{ questionContent }} -->

      <!-- 应用id -->
      <a-form-item label="应用 id">
        {{ appId }}
      </a-form-item>

      <!-- 题目列表 -->
      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space size="large">
          <a-button @click="handleAdd(questionContent.length)">
            底部添加题目
          </a-button>
          <AiGenerateQuestionDrawer 
            :onSSESuccess="onAiGenerateSuccessSSE" 
            :onSSEStart="onSSEStart"
            :onSSEClose="onSSEClose"
            :onSuccess="onAiGenerateSuccess" 
            :appId="appId"
          />
        </a-space>
        
        <!-- 遍历的题目 -->
        <div style="padding-bottom: 20px;border-bottom: 1px dashed #ccc;margin-top: 25px;" v-for="(question,index) in questionContent" :key="index">
          <!-- 题目开头 -->
          <a-space size="large">
            <h3>题目 {{ index + 1 }}</h3>
            <!-- 这里是当前题目后面追加,不是底部追加 -->
            <a-button size="small"  @click="handleAdd(index+1)">
              添加题目
            </a-button>
            <a-button size="small"  status="danger" @click="handleDelete(index)">
              删除题目
            </a-button>
          </a-space>
          <a-form-item  :label="`题目${index + 1} 标题`">
            <a-input v-model="question.title" placeholder="请输入标题..." />
          </a-form-item>
          <!-- 题目结尾 -->

          <!-- 题目选项 -->
          <a-space size="large">
            <h4>题目 {{ index+1 }} 选项列表</h4>
            <a-button size="small"  @click="addQuestionOption(question, question.options.length)">
              底部添加选项
            </a-button>
          </a-space>
          <a-form-item 
            v-for="(option, optionIndex) in question.options" 
            :key="optionIndex"  
            :label="`选项 ${optionIndex + 1}`"
            :content-flex="false"
          >
            <a-form-item label="选项 key">
              <a-input v-model="option.key" placeholder="请输入选项key..." />
            </a-form-item>
            <a-form-item label="选项 值">
              <a-input v-model="option.value" placeholder="请输入选项值..." />
            </a-form-item>
            <a-form-item label="选项结果">
              <a-input v-model="option.result" placeholder="请输入选项结果" />
            </a-form-item>
            <a-form-item label="选项得分">
              <a-input-number
                v-model="option.score"
                placeholder="请输入选项得分"
              />
            </a-form-item>
            <a-space size="large">
              <a-button size="mini"  @click="addQuestionOption(question, optionIndex+1)">
                添加选项
              </a-button>
              <a-button size="mini"  status="danger" @click="delQuestionOption(question,optionIndex)">
                删除选项
              </a-button>
            </a-space>
          </a-form-item>
          
          <!-- 题目选项结尾 -->
        </div>
      </a-form-item>

      <!-- 创建按钮   -->
      <a-form-item>
        <a-button size="large" type="primary" style="width:100%" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
    <!-- {{ form }} -->
  </div>
  
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue';
import API from '@/api'
import {  userRegisterUsingPost } from '@/api/userController';
import message from '@arco-design/web-vue/es/message'
import { useRouter, useRoute } from 'vue-router';
import { addAppUsingPost,editAppUsingPost,getAppVoByIdUsingGet } from '@/api/appController';
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from '@/constant/app';
import { addQuestionUsingPost, editQuestionUsingPost, listQuestionVoByPageUsingPost } from '@/api/questionController';
import AiGenerateQuestionDrawer from './components/AiGenerateQuestionDrawer.vue';

const router = useRouter();


// 定义题目列表
const questionContent = ref<API.QuestionContentDTO[]>([])

// 添加题目
const handleAdd = (index: number) => {
  questionContent.value.splice(index,0,{
    title: '',
    options: []
  })
}

// 删除题目
const handleDelete = (index: number) => {
  questionContent.value.splice(index,1)
}

// 添加题目选项
const addQuestionOption = (question:API.QuestionContentDTO, index: number) => {
  // options可能为空
  if(!question.options) question.options = []
  question.options.splice(index,0,{
    key: '',
    value: ''
  })
}
// 删除题目选项
const delQuestionOption = (question:API.QuestionContentDTO, index: number) => {
  if(!question.options) question.options = []
  question.options.splice(index,1)
}


interface Props {
  appId: string
}

const props = withDefaults(defineProps<Props>(), {
  appId: ()  => {
    return ''
  }
})

const oldQuestion = ref<API.QuestionVO>()

const loadData = async () => {
  if(!props.appId) {
    return
  }
  // 获取最新的一条题目记录
  const res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    current: 1,
    pageSize: 1,
    sortField: 'createTime',
    sortOrder: 'descend'
  })
  if(res.data.code === 0 && res.data.data?.records) {
    oldQuestion.value = res.data.data.records[0]
    if(oldQuestion.value) {
      questionContent.value = oldQuestion.value.questionContent ?? []
    }
  } else {
    message.error('获取数据失败:' +res.data.message)
  }
}
watchEffect(() => { 
  loadData()
})

// 提交表单
const handleSubmit = async ({value, errors}:any) => {
  if(!props.appId || !questionContent.value) return

    let res:any
    // 如果是修改
    if(oldQuestion.value?.id) {
      res = await editQuestionUsingPost({
        id: oldQuestion.value.id,
        questionContent: questionContent.value
      })
    } else {
      res = await addQuestionUsingPost({
        appId: props.appId as any,
        questionContent: questionContent.value
      })
    }
    if(res.data.code === 0) {
      message.success('操作成功,正在跳转应用详情页')
      router.push(`/app/detail/${props.appId}`)
    } else {
      message.error('操作失败:' + res.data.message as string)
    }
}


// 一键生成 传入子组件的函数,获取子组件的ai题目数据
const onAiGenerateSuccess = (result:API.QuestionContentDTO[]) => {
  console.log('no sse')
  message.success(`AI生成题目成功,一共生成了${result.length}道题目`)
  questionContent.value = [...questionContent.value, ...result]
}

// sse实时生成 传入子组件的函数,获取子组件的单个ai题目数据
const onAiGenerateSuccessSSE = (result:API.QuestionContentDTO) => {
  console.log('sse')
  questionContent.value = [...questionContent.value, result]
}

const onSSEStart = (event:any) => {
  message.success('开始生成')
}

const onSSEClose = (event:any) => {
  message.success('生成完毕')
}

</script>
<style lang="scss" scoped>
#addQuestion {
  width: 40vw;
  padding: 20px;
  border-radius: 10px;
  background: rgba(255,255,255,.6);
  margin: 0 auto;
  min-width: 400px;
}
</style>